import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { CartList } from '../../api/shopcart'
import { setCookie, getCookie } from '../../utils/cookie'

export const cartNumAsync = createAsyncThunk('cartNumAsync', async () => {
    const res = await CartList()
    return res.data.data.length
})


export const cartNumSlice = createSlice({
    name: 'cartNumSlice', // 当前store唯一的ID值
    initialState: { // 初始值 value 可以 换成 token
        value: getCookie('cartNum') || 0
    },
    reducers: {
    },
    extraReducers: builder => {
       builder
        .addCase(cartNumAsync.pending, state => { console.log(state, '---pending') }) // action被发出, 还没有最终的结果
        .addCase(cartNumAsync.fulfilled, (state, action) => { // 获取到最终有返回值的结果
            setCookie('cartNum', action.payload)
            state.value = action.payload
        })   
        .addCase(cartNumAsync.rejected, state => { console.log(state, '---rejected') }) // 执行过程中有错或者抛出了异常   
    }
})
export default cartNumSlice.reducer